<template>
    <view class="content">
        <hx-navbar :config="config" />
        <view class="order-add" @click="addorderProduct" v-if="role_id == 2">
            <image src="/static/addorder.png"></image>
        </view>
        <view class="product" v-if="productInfo && productInfo.length > 0">
            <view class="product-box" v-for="(item,index) in productInfo" :key="index">
                <view class="order-content">
                    <view class="order-box">
                        <view class="order-box-cont">
                            <view>产品名称：</view>
                            <view>{{item.product_name}}</view>
                        </view>
                        <view class="order-box-cont">
                            <view>产品数量：</view>
                            <view>{{item.product_num}}</view>
                        </view>
                    </view>
                    <view class="order-box">
                        <view class="order-box-cont">
                            <view>产品型号：</view>
                            <view>{{item.product_model}}</view>
                        </view>
                        <view class="order-box-cont">
                            <view>产品备注：</view>
                            <view>{{item.remark}}</view>
                        </view>
                    </view>
                </view>
                <view class="order-line"></view>
                <view class="order-option">
                    <view class="order-btn order-btn-shipment" v-if="role_id == 2"
                        @click="editorderProduct(item.id)">
                        编辑产品
                    </view>

                    <view class="order-btn order-btn-shipment" v-if="type == 'materialWareHousing'"
                        @click="productInventoryView(item.id)">
                        物料入库
                    </view>

                    <view class="order-btn order-btn-shipment" v-if="type == 'procurement'"
                        @click="productInventoryView(item.id)">
                        采购
                    </view>

                    <view class="order-btn order-btn-shipment" v-if="type == 'productionProgress'"
                        @click="productInfoView(item.id)">
                        生产资料上传
                    </view>
                    <view class="order-btn order-btn-shipment" v-if="type == 'productionQualified'"
                        @click="productInfoView(item.id)">
                        质检资料上传
                    </view>
                    <view class="order-btn order-btn-shipment" v-if="type == 'shipment'"
                        @click="productInfoView(item.id)">
                        发货
                    </view>

                    <view class="order-btn order-btn-check" @click="productInventoryView(item.id)">
                        清单信息
                    </view>
                    <view class="order-btn order-btn-sc" @click="productInfoView(item.id)">
                        生产信息
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
    import {
        product
    } from '@/common/api/order.js'
    export default {
        data() {
            return {
                config: {
                    back: true,
                    title: '交付内容',
                    fontSize: '16px',
                    color: '#ffffff',
                    //背景颜色;参数一：透明度（0-1）;参数二：背景颜色（array则为线性渐变，string为单色背景）
                    backgroundColor: [1, ['#6970ff', '#6970ff']],
                    // 状态栏 ，数组则为滑动变色
                    statusBarBackground: ['', '#ffffff'],
                },
                productInfo: [],
                type: "detail",
                role_id: "",
                id: ""
            }
        },
        onShow() {
            this.orderProductView()
        },
        onLoad(options) {
            this.role_id = uni.getStorageSync("role_id") ? uni.getStorageSync("role_id") : ""
            this.type = options.type
            this.id = options.id
        },
        methods: {
            //清单信息
            productInventoryView(id) {
                uni.navigateTo({
                    url: "/pages/index/product-inventory?id=" + id + "&type=" + this.type,
                })
            },

            //生产信息
            productInfoView(id) {
                uni.navigateTo({
                    url: "/pages/index/product-info?id=" + id + "&type=" + this.type,
                })
            },
            //新增产品
            addorderProduct() {
                uni.navigateTo({
                    url: "/pages/index/addorderProduct?id=" + this.id,
                })
            },
            //编辑产品
            editorderProduct(id) {
                uni.navigateTo({
                    url: "/pages/index/editorderProduct?id=" + id,
                })
            },

            orderProductView() {
                product({
                    id: this.id
                }).then((res) => {
                    this.productInfo = res
                }).catch((err) => {

                });
            },

            // 从URL中提取文件类型（根据后缀名）
            getFileTypeFromUrl(url) {
                if (!url) return null;
                // 匹配URL中最后一个"."后的字符串（忽略参数）
                const match = url.match(/\.([a-zA-Z0-9]+)(\?.*)?$/);
                if (match && match[1]) {
                    const ext = match[1].toLowerCase(); // 转为小写（兼容大小写后缀，如.PDF/.XLSX）
                    // 只保留我们需要的类型（pdf/xlsx/xls）
                    if (['pdf', 'xlsx', 'xls', 'jpg', 'png', 'jpeg'].includes(ext)) {
                        return ext;
                    }
                }
                return null; // 无法识别的类型
            },

            // 通用文件预览（基于URL后缀判断类型）
            previewFile(fileUrl) {
                if (!fileUrl) {
                    uni.showToast({
                        title: '暂无文件',
                        icon: 'none'
                    });
                    return;
                }

                // 1. 通过 URL 获取文件类型
                const fileType = this.getFileTypeFromUrl(fileUrl);
                if (!fileType) {
                    uni.showToast({
                        title: '不支持的文件类型',
                        icon: 'none'
                    });
                    return;
                }

                // 区分文件类型处理
                if (['png', 'jpg', 'jpeg'].includes(fileType)) {
                    // 图片类型，使用 uni.previewImage 预览
                    uni.previewImage({
                        urls: [fileUrl], // 图片预览接口要求传入数组，这里单个图片也用数组形式
                        success: (res) => {
                            console.log(`${fileType} 预览成功`, res);
                        },
                        fail: (err) => {
                            console.error(`${fileType} 预览失败`, err);
                            uni.showToast({
                                title: `打开图片失败`,
                                icon: 'none'
                            });
                        }
                    });
                } else {
                    // 文档类型，走原来的下载 + 打开流程
                    // 2. 下载文件（与之前逻辑一致）
                    uni.downloadFile({
                        url: fileUrl,
                        success: (downloadRes) => {
                            if (downloadRes.statusCode === 200) {
                                // 3. 打开文件（使用解析出的类型）
                                uni.openDocument({
                                    filePath: downloadRes.tempFilePath,
                                    fileType: fileType,
                                    showMenu: true,
                                    success: () => {
                                        console.log(`${fileType} 打开成功`);
                                    },
                                    fail: (err) => {
                                        console.error(`打开${fileType}失败`, err);
                                        uni.showToast({
                                            title: `打开文件失败`,
                                            icon: 'none'
                                        });
                                    }
                                });
                            } else {
                                uni.showToast({
                                    title: '文件下载失败',
                                    icon: 'none'
                                });
                            }
                        },
                        fail: () => {
                            uni.showToast({
                                title: '网络请求失败',
                                icon: 'none'
                            });
                        }
                    });
                }
            }
        }
    }
</script>

<style>
    page {
        background: #f5f5f5;
    }

    .content {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }

    .product {
        display: flex;
        flex-direction: column;
        width: 100%;
    }

    .order-info {
        width: 100%;
        margin-top: 20rpx;
    }

    .product-box {
        background: #fff;
        margin: 10rpx 20rpx;
        display: flex;
        flex-direction: column;
        border-radius: 10rpx;
        padding: 20rpx;
    }

    .order-content {
        display: flex;
        justify-content: space-between;
        font-size: 20rpx;
    }

    .order-box {
        display: flex;
        flex-direction: column;
        width: 50%;
    }

    .order-box-cont {
        display: flex;
        margin-bottom: 15rpx;
    }

    .order-box-cont view:first-of-type {
        width: 30%;
    }

    .order-box-cont view:last-of-type {
        width: 60%;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .order-option {
        display: flex;
        justify-content: flex-end;
    }

    .order-btn {
        padding: 6rpx 30rpx;
        font-size: 20rpx;
        border: 1rpx solid #d5d5d5;
        border-radius: 30rpx;
        margin-left: 10rpx;
    }


    .order-btn-check {
        color: #aaaa00;
        border-color: #aaaa00;
    }

    .order-btn-sc {
        color: #00aaff;
        border-color: #00aaff;
    }

    .order-btn-shipment {
        color: #ffaa00;
        border-color: #ffaa00;
    }

    .order-line {
        border-top: 1rpx solid #f5f5f5;
        margin: 15rpx 0;
    }

    .order-add {
        position: fixed;
        left: 5%;
        bottom: 5%;
        width: 60rpx;
        height: 60rpx;
        border-radius: 60rpx;
        background: #00aaff;
        display: flex;
        justify-content: center;
        align-items: center;
        box-shadow: 0 0 15rpx 8rpx rgba(0, 170, 255, 0.3);
    }

    .order-add image {
        width: 50rpx;
        height: 50rpx;
    }
</style>